/* eslint-disable react/jsx-key */
import DeptSelectDialog from "@/components/DeptSelectModal";
import { DictValueEnum } from "@/components/DictTag";
import Editor from "@/components/Editor";
import PreviewModal from "@/components/HtmlPreviewModal";
import role from "@/services/api/authority/role";
import dept from "@/services/api/organize/dept";
import post from "@/services/api/organize/post";
import { CloseCircleFilled, PlusOutlined } from "@ant-design/icons";
import {
	ModalForm,
	ProFormDateTimePicker,
	ProFormInstance,
	ProFormSelect,
	ProFormSwitch,
	ProFormText,
	ProFormTreeSelect
} from "@ant-design/pro-components";
import { Avatar, Button, Col, Form, Row, Space, Tooltip, TreeSelect } from "antd";
import React, { useRef, useState } from "react";
export type NotifyFormProps = {
	onCancel: () => void;
	onSubmit: (values: NotifyFormData) => Promise<any>;
	open: boolean;
	id: number | undefined;
	filterTypeOptions: DictValueEnum;
	receiveModeOptions: DictValueEnum;
};
export type SelectUserProps = {
	value?: any | undefined;
	onChange?: (value: any) => void;
};
const SelectUser: React.FC<SelectUserProps> = props => {
	const [deptOpen, setDeptOpen] = useState<boolean>(false);
	const { value, onChange = () => {} } = props;
	const [values, setValues] = useState<any>(value);
	// 回调change事件
	const triggerChange = (changedValue: any) => {
		console.log(value);
		setValues(changedValue);
		onChange?.(changedValue);
	};
	const [userOpertionIndex, setUserOpertionIndex] = useState<number | null>(null);
	const handleMouseUserEnter = (index: number) => {
		setUserOpertionIndex(index);
	};

	const handleMouseUserLeave = () => {
		setUserOpertionIndex(null);
	};
	const onRemoveUserFilterCondition = (id: any) => {
		// const recipientFilterCondition = formRef.current?.getFieldValue('recipientFilterCondition');
		const newFilterCondition: any[] = [];
		values.forEach((item: any) => {
			if (item?.id !== id) {
				newFilterCondition.push(item);
			}
		});
		triggerChange(newFilterCondition);
	};
	return (
		<>
			<Space direction="vertical">
				<Space>
					<Space size={[4, 5]} wrap>
						<Button
							type="primary"
							shape="circle"
							onClick={() => {
								setDeptOpen(true);
							}}
						>
							<PlusOutlined />
						</Button>

						{values && (
							<>
								{values?.map((item: any, index: React.Key | null | undefined) => {
									return (
										<Tooltip placement="bottom" title={item?.realName}>
											<Avatar
												// @ts-ignore
												onMouseEnter={() => handleMouseUserEnter(index)}
												onMouseLeave={() => handleMouseUserLeave()}
												key={item?.id}
												style={{ backgroundColor: item?.color, position: "relative" }}
											>
												{item?.realName?.charAt(0)}
											</Avatar>
											{userOpertionIndex === index && (
												<CloseCircleFilled
													// @ts-ignore
													onMouseEnter={() => handleMouseUserEnter(index)}
													onMouseLeave={() => handleMouseUserLeave()}
													onClick={() => {
														onRemoveUserFilterCondition(item?.id);
													}}
													style={{
														fontSize: "16px",
														// color: 'white',
														position: "absolute",
														zIndex: 1,
														marginTop: "-5px",
														marginLeft: "-8px",
														cursor: "pointer"
													}}
												/>
											)}
										</Tooltip>
									);
								})}
							</>
						)}
					</Space>
				</Space>
				{/* <span style={{ color: '#ff4d4f' }}>请选择接收用户</span> */}
			</Space>
			<DeptSelectDialog
				multiple={true}
				open={deptOpen}
				onConfirm={values => {
					triggerChange(values);
					setDeptOpen(false);
				}}
				onCancel={() => {
					setDeptOpen(false);
				}}
			/>
		</>
	);
};
export type NotifyFormData = Record<string, unknown> & Partial<API.Message.NotifyBo>;

const NotifyForm: React.FC<NotifyFormProps> = props => {
	const titles = ["发布公告", "编辑公告"];
	const [title, setTitle] = useState(titles[0]);
	const { open, onCancel, filterTypeOptions, receiveModeOptions, id, onSubmit } = props;
	const [previewOpen, setPreviewOpen] = useState<boolean>(false);
	const formRef = useRef<ProFormInstance>();
	const [immortalShow, setImmortalShow] = useState<boolean>(true);
	const [submitType, setSubimitType] = useState<string>("add");
	const [fileType, setFileterType] = useState<any>();

	// 关闭
	const handleCancel = () => {
		setTitle(titles[0]);
		onCancel();
	};
	// 表单提交
	const handleFinish = async (values: Record<string, any>) => {
		console.log("submitType", submitType);
		if (submitType === "add") {
			values.status = "2";
		} else {
			values.status = "1";
		}
		// @ts-ignore
		return onSubmit({
			...(values as NotifyFormData),
			id: id ? id : undefined
		} as NotifyFormData);
	};
	const editorValidator = (_: any, value: any) => {
		if (value.length > 0) {
			return Promise.resolve();
		}
		return Promise.reject(new Error("Price must be greater than zero!"));
	};
	const selectUserValidator = (_: any, value: any) => {
		console.log(value);
		if (value.length > 0) {
			return Promise.resolve();
		}
		return Promise.reject(new Error("Price must be greater than zero!"));
	};

	return (
		<>
			<ModalForm<NotifyFormData>
				width={"70vw"}
				title={title}
				key="id"
				open={open}
				layout="vertical"
				formRef={formRef}
				submitter={{
					render: (props, doms) => {
						console.log(props);
						return [
							doms[0],
							<Button
								key="preview"
								onClick={() => {
									setPreviewOpen(true);
									// setSubimitType('add');
									// props.submit();
								}}
							>
								预览
							</Button>,
							<Button
								key="add"
								type="primary"
								onClick={() => {
									setSubimitType("add");
									props.submit();
								}}
							>
								仅保存
							</Button>,
							<Button
								key="push"
								type="primary"
								onClick={() => {
									setSubimitType("push");
									props.submit();
								}}
							>
								保存并发布
							</Button>
						];
					}
				}}
				modalProps={{
					centered: true,
					destroyOnClose: true,
					onCancel: () => {
						handleCancel();
					}
				}}
				onFinish={handleFinish}
			>
				<Row gutter={24}>
					<Col span={17}>
						<ProFormText
							name="title"
							fieldProps={{
								count: {
									max: 50,
									show: true,
									strategy: txt => txt.length
								}
							}}
							rules={[{ required: true, message: "请输入标题" }]}
							label="标题"
							placeholder="请输入标题"
						/>
						<Form.Item
							name="content"
							label="内容"
							valuePropName="content"
							rules={[{ required: true, message: "请输入内容", validator: editorValidator }]}
						>
							<Editor />
						</Form.Item>
					</Col>
					<Col span={7}>
						<ProFormSelect
							mode="multiple"
							name="receiveMode"
							label="接收方式"
							valueEnum={receiveModeOptions}
							placeholder="请选择接收方式"
							rules={[{ required: true, message: "请选择接收方式" }]}
						/>
						<ProFormSelect
							name="recipientFilterType"
							label="筛选类型"
							valueEnum={filterTypeOptions}
							placeholder="请选择筛选类型"
							rules={[{ required: true, message: "请选择筛选类型" }]}
							fieldProps={{
								onChange: value => {
									formRef.current?.setFieldValue("recipientFilterCondition", undefined);
									setFileterType(value);
								}
							}}
						/>
						{fileType === "2" && (
							<ProFormSelect
								mode="multiple"
								name="recipientFilterCondition"
								label="接收角色"
								fieldProps={{
									fieldNames: {
										label: "roleName",
										value: "id"
									}
								}}
								request={async () => {
									return role.optionSelecet().then(res => {
										return res.data;
									});
								}}
								placeholder="请选择接收方式"
								rules={[{ required: true, message: "请选择接收方式" }]}
							/>
						)}
						{fileType === "6" && (
							<ProFormSelect
								mode="multiple"
								name="recipientFilterCondition"
								label="接收职位"
								fieldProps={{
									fieldNames: {
										label: "name",
										value: "id"
									}
								}}
								request={async () => {
									return post.optionSelecet().then(res => {
										return res.data;
									});
								}}
								placeholder="请选择接收方式"
								rules={[{ required: true, message: "请选择接收方式" }]}
							/>
						)}
						{fileType === "3" && (
							<ProFormTreeSelect
								name="recipientFilterCondition"
								label="接收部门"
								allowClear
								placeholder="请输入用户所属部门"
								rules={[
									{
										required: true,
										message: "请输入用户所属部门"
									}
								]}
								request={async () => {
									return dept.getList().then((res: any) => {
										return res.data;
									});
								}}
								fieldProps={{
									treeCheckable: true,
									showCheckedStrategy: TreeSelect.SHOW_CHILD,
									multiple: true,
									fieldNames: {
										label: "deptName",
										value: "id"
									}
								}}
							/>
						)}
						<ProFormSwitch
							name="immortal"
							label="是否永久有效"
							initialValue={true}
							rules={[{ required: true, message: "筛选类型!" }]}
							fieldProps={{
								onChange: value => {
									setImmortalShow(value);
									// setDataScopeType(value);
								}
							}}
						/>
						{!immortalShow && (
							<ProFormDateTimePicker
								required={!immortalShow}
								width={"lg"}
								name="deadline"
								label="截至日期"
								rules={[
									{ required: true, message: "截至日期!" },
									({ getFieldValue }) => ({
										validator(_, value) {
											if (!getFieldValue("immortal") && value) {
												return Promise.resolve();
											}
											return Promise.reject(new Error("请选择截止时间"));
										}
									})
								]}
							/>
						)}
						{fileType === "5" && (
							<Form.Item
								name="recipientFilterCondition"
								label="接收用戶"
								valuePropName="recipientFilterCondition"
								rules={[{ required: true, message: "请选择接收用户", validator: selectUserValidator }]}
							>
								<SelectUser />
							</Form.Item>
						)}
					</Col>
				</Row>
			</ModalForm>
			<PreviewModal
				zIndex={1001}
				open={previewOpen}
				title="预览"
				width={"70%"}
				onCancel={() => {
					setPreviewOpen(false);
				}}
				value={formRef?.current?.getFieldValue("content")}
			/>
		</>
	);
};
export default NotifyForm;
